package Threadtest;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class test8_ProductConsumer {
    public static void main(String[] args) {
        BlockingQueue<Integer> q=new ArrayBlockingQueue<>(2);
        product product = new product(q);
        consumer consumer = new consumer(q);

        for (int i = 0; i < 3; i++) {
          new Thread(product).start();
          new Thread(consumer).start();


        }



    }
}
class product implements Runnable{
    //阻塞队列
    BlockingQueue<Integer> queue;
    Lock lock=new ReentrantLock();

    public product(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }
    static AtomicInteger n = new AtomicInteger(0);
    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (n.get()<100){
                    Thread.sleep(10);
                    int num = n.getAndIncrement();
                    System.out.println(Thread.currentThread().getName() + "生成了" + num);
                    queue.put(num);
                }else {
                    break;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }

    }

class consumer implements Runnable{
    //阻塞队列
    BlockingQueue<Integer> queue;

    public consumer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
            try {
                while (true) {
                    synchronized (consumer.class){
                        Thread.sleep(10);
                        System.out.println(Thread.currentThread().getName() + "消费" + queue.take());
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }
